package com.zjlab.web.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.zjlab.SmConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author xue
 * @create 2022-11-08 10:54
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class PictureController {

    private final SmConfig smConfig;

    private static final String REQUEST_HEAD = "smallScreenDisplay";

    @GetMapping("/{type}/{name}")
    public void downloadImage(@PathVariable("type") String type,
                              @PathVariable("name") String name,
                              HttpServletResponse response) {
        InputStream inputStream;
        if (REQUEST_HEAD.equals(type)) {
            inputStream = PictureController.class.getClassLoader().getResourceAsStream(name);
            if (ObjectUtils.isEmpty(inputStream)) {
                log.error("图片资源不存在{}", name);
                return;
            }
        } else {
            String filePath = smConfig.getImageFilePath() + File.separator + name;
            if (!FileUtil.exist(filePath)) {
                log.error("图片文件不存在:{}", filePath);
                return;
            }
            inputStream = FileUtil.getInputStream(filePath);
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            IoUtil.close(outputStream);
            IoUtil.close(inputStream);
        }
    }

}
